package com.zhiyun.hxzy.controller.user;

import com.zhiyun.hxzy.domain.*;
import com.zhiyun.hxzy.domain.queryvo.ConcernVo;
import com.zhiyun.hxzy.domain.queryvo.PageVo;
import com.zhiyun.hxzy.service.*;
import com.zhiyun.hxzy.domain.Classes;
import com.zhiyun.hxzy.domain.queryvo.Result;
import com.zhiyun.hxzy.domain.Student;
import com.zhiyun.hxzy.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user/student")
@SessionAttributes("registerStudent")
public class UserStudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private HomeWorkService homeWorkService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private AutoLoginService autoLoginService;
    @Autowired
    private ConcernService concernService;

    @RequestMapping("/addPre")
    public String addPre(Model model,HttpServletRequest request) {
        Student student = (Student) request.getSession().getAttribute("student");
        List<Student> students = studentService.addPre(student.getId());
        List<Dictionary> tags = studentService.findByTags();
        for(Dictionary tag :tags ){

        }
        List<Dictionary> contents = studentService.findByContent();
        model.addAttribute("students", students);
        model.addAttribute("studentId", student.getId());
        model.addAttribute("tags", tags);
        model.addAttribute("contents", contents);
        return "user/shangchuan";
    }

    //给学生添加作业
    @RequestMapping("/addHomework")
    public String addHomework(Homework homework, Long[] studentIds, Long studentId,String[] urls) {
        List<Result> results = homeWorkService.uploadImg(urls);
        studentService.addHomework(homework, studentIds, studentId);
        return "redirect:/user/homework/findNotCommentHomeworkByStudent";//上传作业之后跳转的页面
    }

    //登录方式1：手机号 密码登录
    @RequestMapping("/passwordLogin")
    public @ResponseBody Result passwordLogin(HttpServletRequest request, HttpSession session, String phoneNum1, String password, String autologin) throws Exception {
        String uuid = null;
        if (autologin != null){
            String userAgent = request.getHeader("User-Agent");//客户端浏览器信息
            String ip = request.getRemoteAddr();//客户端ip地址
            uuid = ip +""+userAgent;
        }
        Student student = studentService.findByPhoneNumAndPassword(phoneNum1, password);
        if (student != null) {
            AutoLogin autoLogin1 = autoLoginService.find(uuid);
            if (autoLogin1 == null){
                //将uuid、手机号及密码写入数据库
                autoLoginService.add(new AutoLogin(uuid,student.getPhoneNum(),0));
            }else {
                autoLogin1.setPhoneNum(phoneNum1);
                autoLogin1.setIdentity(0);
                autoLoginService.add(autoLogin1);
            }
            request.getSession().setAttribute("student", student);
            return new Result("登录成功",true);
        } else {
            return new Result("手机号或密码错误",false);
        }
    }

    //登录方式2：发送手机验证码
    @RequestMapping("/LoginSendPhoneCode")
    public @ResponseBody Result LoginSendPhoneCode(String phoneNum) {
        Result result = studentService.LoginSendPhoneCode(phoneNum);
        return result;
    }

    //登录方式2：手机号 验证码登录
    @RequestMapping("/phoneCheckCodeLogin")
    public @ResponseBody Result phoneCheckCodeLogin(HttpServletRequest request, String phoneNum, String phoneCheckCode,String autologin) {
        String uuid = null;

        Result result = studentService.loginVerifyCode(phoneNum, phoneCheckCode);
        if (result.isResult()) {
            Student student = studentService.findByPhoneNum(phoneNum);
            if (autologin != null){
                String userAgent = request.getHeader("User-Agent");//客户端浏览器信息
                String ip = request.getRemoteAddr();//客户端ip地址
                uuid = ip +""+userAgent;
            }
            AutoLogin autoLogin1 = autoLoginService.find(uuid);//去后台找数据
            if (autoLogin1 == null){
                autoLoginService.add(new AutoLogin(uuid,phoneNum,0));
            }else {
                autoLogin1.setPhoneNum(phoneNum);
                autoLogin1.setIdentity(0);
                autoLoginService.add(autoLogin1);
            }
            request.getSession().setAttribute("student", student);
            return result;
        } else {
            return result;
        }
    }

    //学生用手机 找回密码
    @RequestMapping("/findPassword")
    public @ResponseBody Result findPassword(HttpServletRequest request, String phoneNum, String phoneCheckCode) {
        Result result = studentService.loginVerifyCode(phoneNum, phoneCheckCode);
        if (result.isResult()) {
            request.getSession().setAttribute("phoneNum", phoneNum);
            return result;
        } else {
            return result;
        }
    }

    //学生重置密码
    @RequestMapping("/resetPassword")
    public String resetPassword(String password,String phoneNum) {
        studentService.resetPassword(password,phoneNum);
        return "user/student_forgetpassword3";
    }

    //学生修改个人信息
    @RequestMapping("/updatePersonalMessage")
    public String updatePersonalMessage(HttpServletRequest request, Student student,Long classId) {
        Student studentNew = studentService.updatePersonalMessage(student,classId);
        request.getSession().setAttribute("student", studentNew);
        return "redirect:/user/homework/findNotCommentHomeworkByStudent?studentId="+student.getId();
    }

    //注销登录
    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        //拿到浏览器信息和当前用户手机号并删除自动登录数据库中的数据
        String uuid = null;
        String userAgent = req.getHeader("User-Agent");//客户端浏览器信息
        String ip = req.getRemoteAddr();//客户端ip地址
        uuid = ip +""+userAgent;
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("student");
        AutoLogin autoLogin = new AutoLogin();
        autoLogin.setUuid(uuid);
        autoLogin.setPhoneNum(student.getPhoneNum());
        autoLoginService.delete(autoLogin);
        session.invalidate();
        return "redirect:/user/student_login.jsp";
    }
    //学生上传头像
    @RequestMapping("/uploadHeaderImg")
    public @ResponseBody Result uploadHeaderImg(String file) {
        return studentService.uploadHeaderImg(file);
    }

    //发送手机验证码
    @RequestMapping("/sendPhoneCode")
    public @ResponseBody Result sendPhoneCode(String phoneNum){
        Result usePhone = studentService.isUsePhone(phoneNum);
        if(usePhone.isResult()){
            studentService.sendCodeToPhone(phoneNum);
            return usePhone;
        }else {
            Result result = new Result("该手机已被注册",false);
            return result;
        }
    }

    //注册:第一步(昵称,手机,邮箱)
    @RequestMapping("/verify")
    public String phoneVerify( String phoneNum, String code, String email, String nickName, ModelMap map){
        //1.判断前台传来的数据是否为空
        if(phoneNum==null || code==null || nickName==null){//当昵称、手机号、验证码有一项为空,则返回注册页面1
            return "redirect:/user/register1.jsp";
        }else {
            Result result = studentService.verifyCode(phoneNum, code);
            if(result.isResult()){//注册第一步通过
                Student student = new Student();
                student.setEmail(email);
                student.setNickName(nickName);
                student.setPhoneNum(phoneNum);
                map.addAttribute("registerStudent",student);
                return "redirect:/user/register2.jsp";//跳转到第二步页面
            }else {
                map.addAttribute("result",result);
                return "redirect:/user/register1.jsp";//失败,返回第一步页面
            }
        }
    }


    //注册:第二步(姓名,班级Id)
    @RequestMapping("/ZcTwo")
    public String registerTwo(HttpServletRequest req, String name, String classId, ModelMap map){
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("registerStudent");
        if(student.getPhoneNum()==null || student.getNickName()==null){//先判断第一步的数据是否存在
            return "redirect:/user/register1.jsp";//若数据有缺失则返回注册页面1
        }else {
            if(name==null || classId==null){//判断注册页面2的数据是否有缺失
                return "redirect:/user/register2.jsp";//若数据有缺失则返回注册页面2
            }else {
                Classes classes = classesService.findById(Long.parseLong(classId));
                student.setClasses(classes);
                student.setName(name);
                map.addAttribute("registerStudent",student);
                return "redirect:/user/register3.jsp";
            }
        }
    }

    //注册:第三部(设置密码)
    @RequestMapping("/ZcThree")
    public String registerThree(HttpServletRequest req,String password) throws Exception {
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("registerStudent");
        if( student.getPhoneNum()==null || student.getNickName()==null ){
            return "redirect:/user/register1.jsp";
        }else if(student.getName()==null || student.getClasses()==null){
            return "redirect:/user/register2.jsp";
        } else if(password==null){
            return "redirect:/user/register3.jsp";
        }else {
            student.setPassword(Md5Util.encodeByMd5(password));
            studentService.addStudent(student);
            session.removeAttribute("registerStudent");
            return "user/register4";
        }
    }

    //register-验证手机号是否被使用
    @RequestMapping("/checkPhone")
    public @ResponseBody Result checkPhoneNum(String phoneNum){
        return studentService.isUsePhone(phoneNum);
    }

    //register-验证码
    @RequestMapping("/checkCode")
    public @ResponseBody Result checkCode(String phoneNum,String code){
        return studentService.verifyCode(phoneNum, code);
    }

    //点关注
    @RequestMapping("/concern")
    public @ResponseBody boolean concern(Long follow,Long toFollow){
        Student one = studentService.getOne(follow);
        Student two = studentService.getOne(toFollow);
        concernService.add(new Concern(one,two));
        studentService.addFansCount(toFollow);
        return true;
    }

    //取消关注
    @RequestMapping("/cancel")
    public @ResponseBody boolean cancel(Long follow,Long toFollow){
        concernService.delete(follow, toFollow);
        studentService.deleteFansCount(toFollow);
        return true;
    }

    //查看我的关注
    @RequestMapping("/findConcern")
    public @ResponseBody
    Page<Concern> findConcern(Long id,@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "9") int pageSize){
        Page<Concern> follow = concernService.follow(id, pageNum, pageSize);
        return follow;
    }

    //查看我的粉丝
    @RequestMapping("/findFans")
    public @ResponseBody
    PageVo findFans(Long id,@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "9") int pageSize){
        Page<Concern> follow = concernService.toFollow(id, pageNum, pageSize);
        List<ConcernVo> concernVos = new ArrayList();
        List<Concern> concerns = follow.getContent();
        for (Concern concern:concerns){
            ConcernVo concernVo = new ConcernVo();
            concernVo.setConcern(concern);
            concernVo.setStatus(concernService.judge(concern.getToFollow().getId(),concern.getFollow().getId()));
            concernVos.add(concernVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setConcernPage(follow);
        pageVo.setConcernVoList(concernVos);
        return pageVo;
    }
}
